package com.qiangzhi.handler;

import com.qiangzhi.constant.MessageConstant;
import com.qiangzhi.exception.BaseException;
import com.qiangzhi.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器 处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获并处理SQL异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        // 处理录入的用户名已存在后出现Duplicate entry '***' for key的异常信息
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 捕获上传文件异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    public Result exceptionHandler(IOException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    /**
     * 捕获并处理所有RequestBody注解参数验证异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException ex) {
        log.error("异常信息：{}", ex.getBindingResult().getFieldError().getDefaultMessage());
        return Result.error(ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 捕获并处理所有RequestParam注解数据验证异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result exceptionHandler(BindException ex) {
        log.error("异常信息：{}", ex.getBindingResult().getFieldError().getDefaultMessage());
        return Result.error(ex.getBindingResult().getFieldError().getDefaultMessage());
    }

}
